<?php

namespace App\Tools;

use App\Models\User;

class Token
{

    private static $token;

    public static $uid;

    public static $ttl = 9000;

    /**
     * 新用户设置Token
     * @param $uid
     * @return array
     */
    public static function setUser($uid)
    {

        self::$token = 'token:'.md5(uniqid(microtime(true),true));
        Redis::getInstance()->hSet(self::getToken(),'uid',$uid);
        self::refresh();//设置生存时间
        $data = [
            'token' => self::$token,
            'expiry_time' => date('Y-m-d H:i:s',time()+self::$ttl)
        ];
        return $data;
    }

    /**
     * 设置用户的扩展信息
     * @param string $key
     * @param string $value
     * @return bool
     */
    public static function setInfo($key,$value)
    {
        return Redis::getInstance()->hSet(self::getToken(),$key,$value);
    }

    /**
     * 获得Token
     * @return mixed
     * @throws \Exception
     */
    public static function getToken()
    {
        if (empty(self::$token)) {
            return null;
            throw new \Exception('请先设置Token');
        }
        return self::$token;
    }

    /**
     * 设置Token
     * @param string $token
     * @return mixed
     * @throws \Exception
     */
    public static function setToken($token)
    {
        self::$token = $token;
        return true;
    }

    /**
     * 获取用户的信息
     * @return mixed
     */
    public static function  getUserInfo(){
       $uid = Redis::getInstance()->hGet(self::getToken(),'uid');
       if(!is_numeric($uid)){
           return null;
       }
       self::refresh();
       $data = User::find($uid);
       return $data;
    }

    /**
     * 获取用户的信息
     * @param $key
     * @return string
     */
    public static function  get($key){
       $value = Redis::getInstance()->hGet(self::getToken(),$key);
       return $value;
    }

    /**
     * 获得用户全部信息
     * @return array
     */
    public static function  getInfo(){
       $data = Redis::getInstance()->hGetAll(self::getToken());
       return $data;
    }

    /**
     * 刷新Token
     */
    private static function refresh()
    {
        return Redis::getInstance()->expire(self::getToken(),self::$ttl);
    }

    /**
     * 移除Token
     * @return int
     * @throws \Exception
     */
    public static function forget()
    {
        return Redis::getInstance()->del(self::getToken());
    }
}
